package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.pojo.Player;
import com.example.demo.pojo.PlayerDto;
import com.example.demo.pojo.R;
import com.example.demo.pojo.UserInfoVo;
import com.example.demo.service.PlayerService;
import com.example.demo.util.IdThreadLocal;
import com.example.demo.util.TokenUtil;
import io.minio.*;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.nio.ch.IOUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class PlayerController {
    @Autowired
    private PlayerService playerService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.legendPhotoUrl}")
    private String photoUrl;
    @Value("${minio.avatarUrl}")
    private String avatarUrl;

    @GetMapping("/getAllPlayer")
    public R<List<Player>> getAllPlayer(){
        //获取拦截器添加的用户id
        System.out.println(IdThreadLocal.get());
        return R.success(playerService.getBaseMapper().selectList(null));

    }
    @GetMapping("/getPlayer")
    public R<List<Player>> getPlayer(@RequestParam("name") String name){
        System.out.println(name);
        QueryWrapper<Player> qw =new QueryWrapper<>();
        qw.lambda().like(StringUtils.isNotBlank(name),Player::getName,name);
        qw.orderByAsc("name");
        List<Player> players = playerService.getBaseMapper().selectList(qw);

        return R.success(players);

    }

    @PostMapping("/register")
    public R register(@RequestBody Player player){
        String password=player.getPassword();
        String pw = DigestUtils.md5DigestAsHex(password.getBytes());
        player.setPassword(pw);
        if(playerService.save(player)){
            return R.success(player.getName());
        }
        else {
            return R.error("注册失败",500);
        }
    }

    @PostMapping("/uploadPhoto")
    public R uploadPhoto(@RequestParam("file") MultipartFile multipartFile,@RequestParam("name") String fileName) throws Exception{
        System.out.println(fileName);
        PutObjectArgs putObjectArgs=PutObjectArgs.builder()
                .object(fileName)
                .contentType("image/jpeg")
                .bucket("legendphoto").stream(multipartFile.getInputStream(),multipartFile.getSize(),-1).build();
        minioClient.putObject(putObjectArgs);

        return R.success("ok");
    }
    @PostMapping("/downloadPhoto")
    public R downPhoto(@RequestParam("name") String fileName,HttpServletResponse response) throws Exception{
       GetObjectArgs getObjectArgs=GetObjectArgs.builder()
                .object(fileName).bucket("legendphoto").build();
        InputStream in = minioClient.getObject(getObjectArgs);
        response.setHeader("Content-Disposition","attachment; fileName=" + fileName);
        IOUtils.copy(in,response.getOutputStream());

        return R.success("ok");
    }



    @PostMapping("/uploadAvatar")
    public R uploadAvatar(@RequestParam("file") MultipartFile multipartFile) throws Exception{
        String id =IdThreadLocal.get().toString();
        PutObjectArgs putObjectArgs=PutObjectArgs.builder()
                .object("/avatar/"+id+".jpg")
                .contentType("image/jpeg")
                .bucket("legendphoto").stream(multipartFile.getInputStream(),multipartFile.getSize(),-1).build();
        minioClient.putObject(putObjectArgs);

        return R.success("ok");
    }





    @PostMapping("/login")
    public R login(@RequestBody PlayerDto playerDto, HttpServletResponse response){
        System.out.println(playerDto.getPhone());
        Player player = playerService.getPlayerByPhone(playerDto.getPhone());
        if (player ==null){
            return R.error("无此用户",500);
        }
        else if (!player.getPassword().equals(DigestUtils.md5DigestAsHex(playerDto.getPassword().getBytes()))){
            return R.error("密码错误",500);
    }
        else {
            String token= tokenUtil.generateToken(player);
            System.out.println(token);
            response.setHeader("Token",token);
            Map map=new HashMap();
            map.put("token",token);
            return R.success(map);
        }
    }
    @GetMapping("/info")
    public R userInfo(@RequestParam("Token") String token){
        Integer id = tokenUtil.verify(token);
        Player player = playerService.getBaseMapper().selectById(id);
        UserInfoVo userInfoVo=new UserInfoVo();
        BeanUtils.copyProperties(player,userInfoVo);
        System.out.println(userInfoVo.getId());
        userInfoVo.setAvatar(avatarUrl+userInfoVo.getId()+".jpg");
        System.out.println(avatarUrl+userInfoVo.getId()+".jpg");
        return R.success(userInfoVo);
    }


    @PostMapping("/logout")
    public R logout(HttpServletRequest request,@RequestHeader("Token") String token){
        System.out.println(redisTemplate);
        redisTemplate.opsForValue().set(IdThreadLocal.get().toString(),token,tokenUtil.getEtime());
        System.out.println(token);
        return R.success("登出成功");
    }


    @PostMapping("/updatePlayer")
    public R updatePlayer(@RequestBody Player player, HttpServletResponse response){
        String password=player.getPassword();
        String pw = DigestUtils.md5DigestAsHex(password.getBytes());
        player.setPassword(pw);
        playerService.updateById(player);
        return R.success("更新成功");
    }
    @GetMapping("/getId")
    public R getId(String name){
        QueryWrapper<Player> qw=new QueryWrapper<>();
        qw.lambda().eq(Player::getName,name);
        Player player = playerService.getBaseMapper().selectOne(qw);
        String url=avatarUrl+player.getId().toString()+".jpg";
        return R.success(url);
    }


}
